
package com.shiku.imserver.message.hander;

import com.shiku.imserver.CoreService;
import com.shiku.imserver.cluster.ImClusterServiceIfc;
import com.shiku.imserver.common.annotation.MessageCommandAnnotation;
import com.shiku.imserver.common.hander.AbstractMessageHandler;
import com.shiku.imserver.common.message.AuthMessage;
import com.shiku.imserver.common.message.AuthRespMessage;
import com.shiku.imserver.common.message.PacketVO;
import com.shiku.imserver.common.packets.ImPacket;
import com.shiku.imserver.common.utils.ProBufUtils;
import com.shiku.imserver.common.utils.StringUtils;
import com.shiku.imserver.message.MessageFactory;
import com.shiku.imserver.service.IMBeanUtils;
import com.shiku.utils.StringUtil;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;

public class UserMessageHandler extends AbstractMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(UserMessageHandler.class);

    public UserMessageHandler() {
    }

    @MessageCommandAnnotation(
            command = 5
    )
    public PacketVO authMessageHandler(ImPacket packet, ChannelContext channelContext) {
        try {
            if (null == packet) {
                logger.info("authMessageHandler packet is null ");
            }

            AuthMessage message = (AuthMessage) ProBufUtils.decoderMessageBody(packet.getBytes(), com.shiku.imserver.common.proto.MessageProBuf.AuthMessage.getDescriptor(), AuthMessage.class);
            if (null == message) {
                logger.info("authMessageHandler message is null ");
            }

            String from = message.getMessageHead().getFrom();
            logger.info("user auth userId > {} ", from);
            String to = message.getMessageHead().getTo();
            String password = message.getPassword();
            String token = message.getToken();
            AuthRespMessage authResp = new AuthRespMessage();
            authResp.setMessageHead(MessageFactory.copyeMessageHead(message.getMessageHead()));
            authResp.getMessageHead().setChatType((byte) 10);
            String userId = CoreService.parseBareUserId(from);
            String resource = CoreService.parseResource(from);
            if (StringUtil.isEmpty(password) && !"mp".equals(resource)) {
                if ("Server".equals(resource)) {
                    Tio.bindToken(channelContext, token);
                    if (!IMBeanUtils.getImconfig().getServerToken().equals(token)) {
                        logger.warn(" {} token  认证失败  {}  ", from, token);
                        authResp.setStatus((byte) 0);
                        authResp.setArg("im 认证失败 ! ");
                        PacketVO authRespPacket = MessageFactory.createAuthRespPacket(authResp);
                        return authRespPacket;
                    }
                } else {
                    Tio.bindToken(channelContext, token);
                    String tokenUserId = IMBeanUtils.getRedisService().getUserIdByToken(token);
                    if (StringUtils.isEmpty(tokenUserId) || !tokenUserId.equals(userId)) {
                        logger.warn(" {} token  认证失败  {}  ", from, token);
                        authResp.setStatus((byte) 0);
                        authResp.setArg("im 认证失败 ! ");
                        PacketVO authRespPacket = MessageFactory.createAuthRespPacket(authResp);
                        return authRespPacket;
                    }
                }
            }

            ChannelContext channelContext2 = CoreService.getChannelContextByUserIdResource(channelContext.groupContext, userId, resource);
            if (null != channelContext2 && !channelContext2.getId().equals(channelContext.getId())) {
                String errArg = from + " 已经登陆  被挤下线";
                logger.info(errArg);
                CoreService.notifyUserConflict(channelContext2, from, errArg);
            }

            if (!StringUtils.isEmpty(resource)) {
                channelContext.setAttribute("resource", resource);
            }

            Tio.bindUser(channelContext, userId);
            Set<String> listResources = CoreService.getChannelContextResources(channelContext.groupContext, userId);
            String resources = StringUtils.listToString(listResources, ",");
            authResp.setStatus((byte) 1);
            authResp.setToken(token);
            authResp.setResources(resources);
            ImPacket result = MessageFactory.createAuthRespIMPacket(authResp);
            Tio.sendToUser(channelContext.groupContext, userId, result);
            CoreService.userOnline(from, userId, channelContext);
            ImClusterServiceIfc imClusterService = IMBeanUtils.getBeanManager().getImClusterService();
            if (null != imClusterService) {
                imClusterService.notifyClusterUserStatus(userId, resource, true);
            }
        } catch (Exception var16) {
            var16.printStackTrace();
        }

        return null;
    }

    @MessageCommandAnnotation(
            command = 1
    )
    public PacketVO onAfterHandshakedHandler(ImPacket packet, ChannelContext channelContext) {
        try {
            if (null == packet.getBytes()) {
                return null;
            }

            String param = new String(packet.getBytes());
            logger.info(" param ====> " + param);
            ImPacket imPacket = new ImPacket("111111111111".getBytes());
            Tio.send(channelContext, imPacket);
        } catch (Exception var5) {
            var5.printStackTrace();
        }

        return null;
    }
}
